const {app, BrowserWindow, globalShortcut, screen, ipcMain, Menu} = require('electron/main')
const path = require('node:path')
const sqlite3 = require('sqlite3');
const {exec} = require('child_process');
const os = require("os");
const iconv = require('iconv-lite');
const db = new sqlite3.Database("C:/Users/zhangcong/codegen.db");

Menu.setApplicationMenu(null)

function createWindow() {
    const win = new BrowserWindow({
        width: screen.getPrimaryDisplay().workAreaSize.width,
        height: screen.getPrimaryDisplay().workAreaSize.height,
        webPreferences: {
            preload: path.join(__dirname, 'preload.js')
        }
    })

    globalShortcut.register('CommandOrControl+Shift+i', function () {
        win.webContents.toggleDevTools() // 打开/关闭控制台
    })

    globalShortcut.register('CommandOrControl+Shift+r', function () {
        win.webContents.reload() // 刷新页面
    })

    if (app.isPackaged) {
        win.loadFile(path.join(__dirname, '../dist/index.html'))
    } else {
        win.loadURL("http://localhost:8080/")
        win.webContents.openDevTools()
    }
}

app.whenReady().then(() => {

    ipcMain.handle('createDb', (event) =>
        new Promise((resolve, reject) => {
            const sql = 'CREATE TABLE IF NOT EXISTS my_memo ([id] integer primary key autoincrement, [memo] text, [date_time] datetime)'
            db.run(sql, err => {
                if (err) reject(err);
                resolve();
            });
        })
    )

    ipcMain.handle('selectAll', (event) =>
        new Promise((resolve, reject) => {
            const sql = 'SELECT * FROM my_memo'
            db.serialize(() => {
                db.all(sql, (err, rows) => {
                    if (err) reject(err);
                    resolve(rows);
                });
            });
        })
    );

    ipcMain.handle('insertData', (event, text) =>
        new Promise((resolve, reject) => {
            const sql = 'INSERT INTO my_memo (memo, date_time) VALUES (?, datetime("now", "localtime"))'
            db.run(sql, text, err => {
                if (err) reject(err);
                resolve();
            });
        })
    )

    ipcMain.handle('javaData', (event) =>
        new Promise((resolve, reject) => {
            const cmd = 'D:\\dev\\graalvm-ce-java17-22.3.3\\bin\\java.exe -jar D:\\dev\\workspaces\\codegen-app\\codegen-java\\target\\codegen-java.jar'
            exec(cmd, {encoding: 'binary', maxBuffer: 10 * 1024 * 1024}, (error, stdout, stderr) => {
                const encoding = os.platform() === 'win32' ? 'cp936' : 'utf-8';
                if (error) {
                    reject(iconv.decode(Buffer.from(error.message, 'binary'), encoding));
                } else {
                    resolve(iconv.decode(stdout, encoding));
                }
            })
        })
    )

    createWindow()

    app.on('activate', () => {
        if (BrowserWindow.getAllWindows().length === 0) {
            createWindow()
        }
    })
})

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        app.quit()
    }
})